package com.linkq.ipinyin.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.*;

import java.io.ByteArrayInputStream;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Base64;
import java.util.List;
import java.util.Map;

/**
 * @author wangpeng
 * @since 2025-07-01
 **/

public class AppleJwtValidator {
    public static Claims validateAppleJwt(String signedPayload) throws Exception {
        String headerJson = new String(Base64.getUrlDecoder().decode(signedPayload.split("\\.")[0]));
        Map<String, Object> header = new ObjectMapper().readValue(headerJson, Map.class);

        // 2. 获取x5c证书链
        List<String> x5c = (List<String>) header.get("x5c");
        if (x5c == null || x5c.isEmpty()) {
            throw new IllegalArgumentException("Missing x5c certificate chain");
        }

        // 3. 使用第一个证书验证签名
        X509Certificate cert = parseCertificate(x5c.get(0));
        return Jwts.parserBuilder()
                .setSigningKey(cert.getPublicKey()) // 提供公钥
                .build()
                .parseClaimsJws(signedPayload)     // 使用parseClaimsJws()
                .getBody();
    }

    private static X509Certificate parseCertificate(String certStr) throws Exception {
        byte[] certBytes = Base64.getDecoder().decode(certStr);
        return (X509Certificate) CertificateFactory.getInstance("X.509")
                .generateCertificate(new ByteArrayInputStream(certBytes));
    }
}
